<!DOCTYPE html>
<html>
<head>
	<title></title>
	<meta charset="utf-8" />
</head>
<body>

</body>
</html>
<script type="text/javascript">
  //promise
	// 单次
	function runAsync(){
		let p=new Promise(function(rl,rj){
			let arr=[];
			setTimeout(()=>{
				console.log("zhixin")
				console.log(this.arr,rl,rj)//arr没有被保留下来
				rl('随便什么数据')
			},2000)
		});
		return p;
	}
  runAsync().then(res=>{
  	console.log(res);
  })
  //多层
  function runAsync0(str){
    let p=new Promise((rl,rj)=>{
    	setTimeout(()=>{
				rl(str)
			},1000)
    })
    return p;
  }
  runAsync().then(res=>{
  	console.log(res+1);
  	return runAsync0(res+1)
  }).then(res=>{
  	console.log(res+1);
  	return runAsync0(res+1)
  }).then(res=>{
  	console.log(res+1);
  	return runAsync0(res+1)
  }).then(res=>{
  	console.log(res+1);
  	return runAsync0(res+1)
  }).then(res=>{
  	console.log(res+1);
  	return runAsync0(res+1)
  })
  // async
  async function runFun(){
    let r=0;
    r=await (()=>{
      setTimeout(()=>{
        return "timeout"
      },1000);
    })()
    console.log(r) //undefined //并拿不到异步返回的值
  }
  // runFun();
  // 其实async-await是promise和generator的语法糖
  async function runFun0(s=2000){
    let r=await new Promise((resolve,reject)=>{
      setTimeout(()=>{
        resolve("aa");
      },s)
    });
    console.log(r+1);
  }
  // runFun0();
  //await 的作用范围
  async function testFun0(){
    let now=new Date().getTime();
    let r0=await new Promise((rs,rj)=>{
      // await runFun0();//await is only valid in async function
      setTimeout(()=>{
        rs('b?');
      },1000)
    });
    // let r1=await runFun0();//后面的方法都被延时了
    // await runFun0();//后面的方法都被延时了

    let r1;{r1 = await runFun0();}//await 有效 后面的方法都被延时了
    console.log(new Date().getTime()-now)
    console.log('bb',r0);
    console.log('cc',r1);
  }
  // testFun0();

  //测试几个顺序
  function timeout0(n){
    return new Promise((rs,rj)=>{
      setTimeout(()=>{
        console.log("timout0"+n)
        rs(n)
      },1000)
    })
  }
  async function sometimeout(){
    await timeout0(1)
    await timeout0(2)
    await timeout0(3)
    await timeout0(4)
    //测试会按照顺序执行，一个执行完毕以后再执行下一个
  }
  sometimeout();
</script>